import 'dart:async';
import 'package:app/shared/shared.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:get/get.dart';
import 'auth_controller.dart';

class LoginScreen extends StatefulWidget {
  LoginScreen({Key? key}) : super(key: key);

  @override
  _LoginScreenState createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
  final AuthController controller = Get.arguments;
  String _name = '';
  String _yzm = '';
  bool isShow = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
          elevation: 0,
          backgroundColor: Colors.white,
          iconTheme: IconThemeData(
            color: Colors.black,
          )),
      body: Container(
        color: Colors.white,
        padding: EdgeInsets.symmetric(horizontal: sDefaultMarginPadding * 4),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              margin: EdgeInsets.only(
                  top: MediaQuery.of(context).size.height / 10, bottom: 50),
              child: SvgPicture.asset(
                "assets/icons/logo.svg",
                width: 60,
              ),
            ),
            Container(
              child: Form(
                key: controller.loginFormKey,
                child: Column(
                  children: [
                    TextFormField(
                      controller: controller.loginMobileController,
                      maxLength: 11,
                      cursorColor: Colors.black,
                      decoration: InputDecoration(
                        counterText: '',
                        hintStyle: TextStyle(
                            color: Colors.grey.shade300, fontSize: 14),
                        hintText: '输入您的手机号(登录即注册)',
                        focusedBorder: UnderlineInputBorder(
                            borderSide: BorderSide(
                                color: Colors.grey.shade300, width: 0.5)),
                        enabledBorder: UnderlineInputBorder(
                            borderSide: BorderSide(
                                color: Colors.grey.shade300, width: 0.5)),
                      ),
                      onChanged: (value) {
                        setState(() {
                          _name = value;
                          isShow = _name.length > 10 && _yzm.length == 6;
                        });
                      },
                      validator: (value) {
                        return value!.length >= 6 ? null : '账号最少11个字符';
                      },
                    ),
                    SizedBox(
                      height: 30,
                    ),
                    TextFormField(
                      controller: controller.loginYzmController,
                      maxLength: 6,
                      cursorColor: Colors.black,
                      decoration: InputDecoration(
                          counterText: '',
                          focusColor: Colors.grey.shade300,
                          hintStyle: TextStyle(
                              color: Colors.grey.shade300, fontSize: 14),
                          hintText: '点击右侧按钮来获取验证码',
                          focusedBorder: UnderlineInputBorder(
                              borderSide: BorderSide(
                                  color: Colors.grey.shade300, width: 0.5)),
                          enabledBorder: UnderlineInputBorder(
                              borderSide: BorderSide(
                                  color: Colors.grey.shade300, width: 0.5)),
                          suffixIcon: LoginFormCode(available: true)),
                      onChanged: (value) {
                        setState(() {
                          _yzm = value;
                          isShow = _name.length > 10 && _yzm.length == 6;
                        });
                      },
                      validator: (value) {
                        return value!.length >= 6 ? null : '账号最少6个字符';
                      },
                    ),
                    SizedBox(
                      height: 60,
                    ),
                    TextButton(
                      child: Container(
                        alignment: Alignment.center,
                        width: MediaQuery.of(context).size.width -
                            sDefaultMarginPadding * 4 * 2,
                        height: 48,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(6),
                          color: isShow ? sPrimaryColor : Colors.grey.shade400,
                        ),
                        child: Text(
                          "登录",
                          style: TextStyle(
                              color: isShow ? sTextColor : Colors.white,
                              fontSize: 16),
                        ),
                      ),
                      onPressed: isShow
                          ? () {
                              controller.login(context);
                            }
                          : null,
                    )
                  ],
                ),
              ),
            ),
            Align(
              alignment: Alignment.centerRight,
              child: TextButton(
                  onPressed: () {},
                  child: Text(
                    "忘记密码?",
                    style: TextStyle(color: Colors.grey.shade400),
                  )),
            )
          ],
        ),
      ),
    );
  }
}

// 墨水瓶（`InkWell`）可用时使用的字体样式。
final TextStyle _availableStyle = TextStyle(
  fontSize: 16.0,
  color: const Color(0xFF00CACE),
);

/// 墨水瓶（`InkWell`）不可用时使用的样式。
final TextStyle _unavailableStyle = TextStyle(
  fontSize: 16.0,
  color: const Color(0xFFCCCCCC),
);

class LoginFormCode extends StatefulWidget {
  /// 倒计时的秒数，默认60秒。
  final int countdown;

  /// 用户点击时的回调函数。
  final Function? onTapCallback;

  /// 是否可以获取验证码，默认为`false`。
  final bool available;

  LoginFormCode({
    this.countdown: 60,
    this.onTapCallback,
    this.available: false,
  });

  @override
  _LoginFormCodeState createState() => _LoginFormCodeState();
}

class _LoginFormCodeState extends State<LoginFormCode> {
  /// 倒计时的计时器。
  Timer? _timer;

  /// 当前倒计时的秒数。
  late int _seconds;

  /// 当前墨水瓶（`InkWell`）的字体样式。
  TextStyle inkWellStyle = _availableStyle;

  /// 当前墨水瓶（`InkWell`）的文本。
  String _verifyStr = '获取验证码';

  @override
  void initState() {
    super.initState();
    _seconds = widget.countdown;
  }

  /// 启动倒计时的计时器。
  void _startTimer() {
    // 计时器（`Timer`）组件的定期（`periodic`）构造函数，创建一个新的重复计时器。
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      if (_seconds == 0) {
        _cancelTimer();
        _seconds = widget.countdown;
        inkWellStyle = _availableStyle;
        setState(() {});
        return;
      }
      _seconds--;
      _verifyStr = '已发送$_seconds' + 's';
      setState(() {});
      if (_seconds == 0) {
        _verifyStr = '重新发送';
      }
    });
  }

  /// 取消倒计时的计时器。
  void _cancelTimer() {
    // 计时器（`Timer`）组件的取消（`cancel`）方法，取消计时器。
    _timer?.cancel();
  }

  @override
  Widget build(BuildContext context) {
    // 墨水瓶（`InkWell`）组件，响应触摸的矩形区域。
    return widget.available
        ? InkWell(
            child: Text(
              '  $_verifyStr  ',
              style: inkWellStyle,
            ),
            onTap: (_seconds == widget.countdown)
                ? () {
                    _startTimer();
                    inkWellStyle = _unavailableStyle;
                    _verifyStr = '已发送$_seconds' + 's';
                    setState(() {});
                    widget.onTapCallback!();
                  }
                : null,
          )
        : InkWell(
            child: Text(
              '  获取验证码  ',
              style: _unavailableStyle,
            ),
          );
  }
}
